<?php

namespace App\Http\Controllers\Api;

use App\Coupons;
use App\DistributionOrder;
use App\Exceptions\WechatException;
use App\FeeRule;
use App\Http\Services\DomainManager;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\Merchant;
use App\MerchantMedicine;
use App\OrderAddress;
use App\OrderItem;
use App\Orders;
use App\User;
use App\UserCoupon;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Log;

class OrderController extends Controller
{
    /**@author cmj
     * 获取我订单列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getMyOrderList(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $status=$request->input('status');
        $page       =$request ->input('page')  ? $request->input('page')  : 1;
        $limit      =$request ->input('limit') ? $request->input('limit') : 2;
        $page_info=[
            'page'=>$page,
            'limit'=>$limit,
            'total'=>0
        ];
        $page=$page-1;
        $orders=Orders::whereUserId($user->id)
            ->whereEnterpriseId($enterpriseId);
        if (!is_null($status) && $status !=='' && in_array($status,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])){
//            $orders=$orders->whereStatus($status);
            if ($status == 9)
                $orders=$orders->whereIn('status',[5,7,8]);
            else
                $orders=$orders->whereStatus($status);
        }
        $page_info['total']=$orders->count();
        $orders = $orders->orderByDesc('id')->offset($page*$limit)->limit($limit)->get();
        if (count($orders) > 0){
            foreach ($orders as $order){
                $order->status_name     =self::getStatusName($order->status);
                $order->order_items     =OrderItem::getOrderItem($order->id);
                $order->merchant_name   =Merchant::getMerchantName($order->merchant_id);
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$orders,'page_info'=>$page_info]);
    }

    /**@author cmj
     * 获取我的订单详情
     * @param Request $request
     * @return JsonResponse
     */
    public function getMyOrderDetail(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
        $order_num=$request->input('order_num');
        if (!$order_num)
            return response()->json(['level' => 'error','message' => '参数错误','data' => []]);
        $order=orders::whereUserId($user->id)
            ->whereEnterpriseId($enterpriseId)
            ->whereOrderNum($order_num)->first();
        if (!$order)
            return response()->json(['level' => 'error','message' => '订单不存在','data' => []]);
        $order->status_name=self::getStatusName($order->status);
        $order->order_items     =OrderItem::getOrderItem($order->id);
        $order->merchant_name   =Merchant::getMerchantName($order->merchant_id);
        $merchant = merchant::whereId($order->merchant_id)->whereReview(1)->first();
        $order->merchant_info = $merchant;
        $order->address_info    =OrderAddress::getAddressInfo($order->order_address_id);
        $order->coupon_name = UserCoupon::getUserCouponName($order->coupon_id);
        return response()->json(['level'=>'success','message'=>'success','data'=>$order]);
    }

    public function userCancelOrder(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $order_id   =$request->input('order_id');
        $thisOrder  =orders::whereId($order_id)
            ->whereEnterpriseId($enterpriseId)
            ->whereUserId($user->id)
            ->first();
        if (in_array($thisOrder->status,[0,1])){
            //直接取消
            $thisOrder->status= 6;
            $thisOrder->save();

            /** @var OrderItem $orderItem */
            $orderItemList= OrderItem::getOrderItem($thisOrder->id);
            if(count($orderItemList) > 0){
                foreach ($orderItemList as $orderItem) {
                    $thisMedicine=MerchantMedicine::whereId($orderItem->merchant_medicine_id)->first();
                    if($thisMedicine){
                        $thisMedicine->stock += $orderItem->num;
                        $thisMedicine->save();
                    }
                }
            }

            //取消订单后改变分销订单状态
            DistributionOrder::setDistributionOrderFail($thisOrder->id);

            return response()->json(['level'=>'success','message'=>'已取消']);
        } else {
            $thisOrder->status= 5;
            $thisOrder->save();
            return response()->json(['level'=>'success','message'=>'已提交申请，请等待处理']);
        }
    }

    public function confirmReceive(Request $request){
        $enterpriseId=DomainManager::getEnterpriseId($request);
        if (!$enterpriseId)
            return response()->json(['level'=>'error','message'=>'域名未授权','data'=>[]]);

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $order_id   =$request->input('order_id');
        $thisOrder  =orders::whereId($order_id)
            ->whereEnterpriseId($enterpriseId)
            ->whereUserId($user->id)
            ->first();
        if ($thisOrder->status!=3){
            return response()->json(['level'=>'error','message'=>'当前状态不能收货哦']);
        } else {
            $thisOrder->status= 4;
            $thisOrder->receive_time= date('Y-m-d H:i:s');
            $thisOrder->save();

            //确认订单后改变分销订单状态
            DistributionOrder::setDistributionOrderSuccess($thisOrder->id);

            return response()->json(['level'=>'success','message'=>'已确认收货']);
        }
    }

    public function prescriptionOrderHandle(Request $request){
        $orderNum = $request->input('order_num') ?? '';

        $order = Orders::whereOrderNum($orderNum)->first();
        if(!$order)
            return response()->json(['level' => 'error','message' => '订单不存在']);

        try {
            $result = PaymentController::prescriptionHandle($order);
        } catch (\Exception $e){
            return response()->json(['level' => 'error','message' => $e->getTraceAsString()]);
        }

        return response()->json(['level' => 'success','message' => "提交成功",'data' =>$result]);
    }

    /**@author cmj
     * 订单状态值对应状态
     * @param $status
     * @return string
     */
    public static function getStatusName($status){
        if ($status==1)
            return '待支付';
        if ($status==2)
            return '待发货';
        if ($status==3)
            return '待收货';
        if ($status==4)
            return '已完成';
        if ($status==5)
            return '申请退款';
        if ($status==6)
            return '已取消';
        if ($status==7)
            return '已退款';
        if ($status==8)
            return '申请未通过';
        if ($status==9)
            return '申请退款/售后(大类)';
        return $status;
    }
    public function test(){
        dump(self::getDistance(23.116809844971,113.39809417725,23.113750,113.403175));
    }

    /**
     * 调用腾讯地图API计算两点路程
     * @param $start_lat
     * @param $start_lng
     * @param $end_lat
     * @param $end_lng
     * @return array
     */
    public static function getDistance($start_lat,$start_lng,$end_lat,$end_lng){
        $url    ='http://apis.map.qq.com/ws/distance/v1/matrix?';
        $from   =$start_lat .','.$start_lng;
        $to     =$end_lat   .','.$end_lng;
        $key    ='YM3BZ-LORCG-BTNQU-IQLQS-BLB3F-KCFG3';
        $sk     ='a3inS5ahkcDLlOf1yKZN0FpEeGxHJew';

        $sign=md5('/ws/distance/v1/matrix?from='.$from.'&key=YM3BZ-LORCG-BTNQU-IQLQS-BLB3F-KCFG3'.'&mode=driving&to='.$to.'a3inS5ahkcDLlOf1yKZN0FpEeGxHJew');
        $request_url=$url.'mode=driving&key=YM3BZ-LORCG-BTNQU-IQLQS-BLB3F-KCFG3&from='.$from.'&to='.$to.'&sig='.$sign;
        try{
            $result =\Requests::get($request_url);
        } catch (Exception $exception){
            Log::error('getDistanceERROR=>'.$exception->getMessage());
            return ['level'=>'error','message'=>'规划路线发生错误:'.$exception->getMessage(),'data'=>[]];
        }
//        return $result;
        if(!$result->success)
            return ['level'=>'error','message'=>'路线规划失败，请稍后重试','data'=>[]];
        $resultInfo = json_decode($result->body);
        if ($resultInfo->status!=0){
            return ['level'=>'error','message'=>$resultInfo->message,'data'=>[]];
        }
        $data=$resultInfo->result->rows;
        $tmp=array_pop($data);
        $data=(array)$tmp->elements[0];
        /** ['distance'=>'','duration'=>''] $data */
        return ['level'=>'success','message'=>'success','data'=>$data];
    }
}
